# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/25 2:22 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : run.py
# @Software: PyCharm

import wave
import sys
from PyQt5.QtWidgets import QWidget, QApplication
from pyqtgraphs.main_window import Ui_Form
from pyqtgraph import mkPen
import numpy as np
import pyqtgraph as pg


class MainWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.ui.graphicsView.setBackground('w')

        # 绑定槽函数
        self.ui.pushButton.clicked.connect(self.wav_paint)

        # 设置数值条数值
        self.ui.verticalSlider.setRange(0, 100)
        self.ui.verticalSlider.valueChanged.connect(self.show_value)

    def show_value(self):
        slider = self.sender()
        self.ui.label.setText(str(slider.value()))
        self.wav_paint(slider.value())

    # 读取波形数据
    def audio_data(self, t):
        file_path = r"../record_audio/output.wav"
        file = wave.open(file_path, "rb")

        audio_params = file.getparams()
        nchannels, sampwidth, framerate, nframes = audio_params[:4]
        # 读取波形数据
        str_data = file.readframes(nframes)
        file.close()

        # 将波形数据转换为数组
        wave_data = np.fromstring(str_data, dtype=np.short)

        # 设置数组的形状
        wave_data.shape = -1, nchannels
        wave_data = wave_data.T

        # 小波阀值去白噪，获取最终Y轴波形数组
        wave_data[abs(wave_data) < t] = 0

        # 获取X轴时间数组
        times = np.arange(0, nframes) * (1.0 / framerate)

        return times, wave_data[0]

    # 0数组检测
    def zero_runs(self, a):
        iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))
        absdiff = np.abs(np.diff(iszero))
        ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
        return ranges

    # clear数据清洗
    def data_clear(self, times, wave_data):
        result = self.zero_runs(wave_data)
        for i in result:
            time_tmp = i[1] - i[0]
            # 超过0.25秒则记录数值，44100一秒
            if time_tmp > 11025:
                check_data = np.zeros(time_tmp, dtype=int)
                check_time = times[i[0]:i[1]]
                self.ui.graphicsView.plot(check_time, check_data, pen=mkPen('r'))

                # 设置绘图区域
                region = pg.LinearRegionItem()
                self.ui.graphicsView.addItem(region, ignoreBounds=True)
                # 设置绘图区域宽度
                region.setRegion([times[i[0]], times[i[1]]])
                # 设置绘图区域不可移动
                region.setMovable(False)

                pos_x = (times[i[1]] - times[i[0]]) / 2 + times[i[0]]

                show_times = format(time_tmp/44100, '.5f')

                # 绘制文字
                text = pg.TextItem(
                    html=f'<div style="text-align: center"><span style="color: #FFF;">耗时时长</span><br><span style="color: #c00; font-size: 16pt;">{show_times}</span></div>',
                    anchor=(-0.3, 0.5), angle=45, border='w', fill=(0, 0, 255, 100))

                text.setPos(pos_x, 0)
                arrow = pg.ArrowItem(pos=(pos_x, 0), angle=-45)

                self.ui.graphicsView.addItem(text)
                self.ui.graphicsView.addItem(arrow)

    # 按钮事件
    def wav_paint(self, t):
        # 先清空一次
        self.ui.graphicsView.clear()

        # # 小波阀值获取
        # line = int(self.ui.lineEdit.text())
        # T = line if line else 0

        # 通过阀值生成获取波形
        X, Y = self.audio_data(t)

        # 绘制原生数据
        self.ui.graphicsView.plot(X, Y, pen=mkPen('b'))

        # 绘制关注波形
        self.data_clear(X, Y)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
